package com.lincoln.framework.utils;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.mozilla.javascript.EvaluatorException;

import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

/**
 * 压缩工具
 * @author Rubekid
 *
 */
public class CompressUtils {

	/**
	 * 压缩css
	 * @param css
	 * @throws IOException 
	 */
	public static String compressCss(String css) throws IOException{
		Reader reader = new StringReader(css);
		CssCompressor compressor = new CssCompressor(reader);
		Writer out= new StringWriter();
		compressor.compress(out, -1);
		out.flush();
		out.close();
		return  out.toString();
	}
	
	/**
	 * 压缩javascript
	 * @param javascript
	 * @throws IOException 
	 * @throws EvaluatorException 
	 */
	public static String compressJavascript(String javascript) throws EvaluatorException, IOException{
		Pattern pattern = Pattern.compile("(<script[^>]*>)([\\s\\S]*?)(<\\/script>)");
		Matcher matcher = pattern.matcher(javascript);
		if(matcher.find()){
			StringBuffer stringBuffer;
			matcher = pattern.matcher(javascript);
			while(matcher.find()){
				stringBuffer  = new StringBuffer();
				stringBuffer.append(matcher.group(1));
				stringBuffer.append(compressJavascriptCode(matcher.group(2)));
				stringBuffer.append(matcher.group(3));
				stringBuffer.append("\n");
				javascript = javascript.replace(matcher.group(0), stringBuffer.toString());
			}
		}
		else{
			javascript = compressJavascriptCode(javascript);
		}
		return javascript;
	}
	
	/**
	 * 压缩javaScript源码 不带 script标签
	 * @param code
	 * @throws IOException 
	 * @throws EvaluatorException 
	 */
	public static String compressJavascriptCode(String code) throws EvaluatorException, IOException{
		Reader reader = new StringReader(code);
		JavaScriptCompressor compressor = new JavaScriptCompressor(reader, null);
		Writer out= new StringWriter();
		compressor.compress(out, -1, false, false, false, false);
		out.flush();
		out.close();
		return out.toString();
	}
	
	/**
	 * 压缩html源码(纯html)
	 * @param String code
	 */
	public static String compressHtml(String code){
		code = code.replaceAll("[\\n\\r]", "");
		code = code.replaceAll("<!--.*?-->", "");
		code = code.replaceAll(">\\s+?<", "><");
		return code;
	}
}
